<template>
  <div>
    <h3>比赛成绩</h3>
    <div class="container">
      <vxe-toolbar style="height: 100px;">
        <template #buttons>
          <el-row :gutter="20" type="flex" style="margin-bottom: 20px;">
            <el-col :span="4">
              <el-select v-model="searchForm.areaId" size="small" collapse-tags filterable clearable placeholder="选择区域"
                @change="areaChange">
                <el-option :label="item.name" :value="item.areaId" v-for="(item,index) in areaData"
                  :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-select v-model="searchForm.orgIdStr" size="small" multiple collapse-tags filterable clearable
                placeholder="选择组织机构">
                <el-option :label="item.name" :value="item.orgId" v-for="(item,index) in orgData"
                  :key="index"></el-option>
              </el-select>
              <el-button type="success" size="small" @click="selectOrgAll">全选</el-button>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-select v-model="searchForm.matchLevelStr" size="small" multiple collapse-tags filterable clearable
                placeholder="选择赛事级别">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_match_level"
                  :key="index"></el-option>
              </el-select>
              <el-button type="success" size="small"
                @click="searchForm.matchLevelStr=Object.keys(dict_match_level)">全选</el-button>
            </el-col>
            <el-col :span="4" style="display: flex;">
              <el-select v-model="searchForm.matchKindStr" size="small" multiple collapse-tags filterable clearable
                placeholder="选择赛事类别">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_match_kind"
                  :key="index"></el-option>
              </el-select>
              <el-button type="success" size="small"
                @click="searchForm.matchKindStr=Object.keys(dict_match_kind)">全选</el-button>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.matchEventId" size="small" collapse-tags filterable clearable
                placeholder="选择参赛项目" @change="sportChange">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_match_event"
                  :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="searchForm.matchEventItemId" size="small" collapse-tags filterable clearable
                placeholder="选择参赛小项">
                <el-option :label="item" :value="key" v-for="(item,key,index) in matchEventItemData"
                  :key="index"></el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row :gutter="20" type="flex">
            <el-col :span="5" style="display: flex;">
              <el-button @click="exportEvent" size="small" type="primary" icon="el-icon-download">导出</el-button>
              <el-button @click="printEvent" size="small" type="primary" icon="el-icon-printer">打印</el-button>
            </el-col>
            <el-col :span="5">
              <el-select v-model="searchForm.skillTypeId" size="small" collapse-tags filterable clearable
                placeholder="选择运动等级">
                <el-option :label="item" :value="key" v-for="(item,key,index) in dict_skillType"
                  :key="index"></el-option>
              </el-select>
            </el-col>
            <el-col :span="5">
              <el-input size="small" placeholder="输入名次" type="number" v-model="searchForm.matchRank"></el-input>
            </el-col>
            <el-col :span="6">
              <el-date-picker size="small" v-model="doubleDate" type="daterange" align="right" unlink-panels
                style="width: 80%;" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-col>
            <el-col :span="5" style="display: flex;">
              <el-button type="success" size="small" icon="el-icon-s-promotion" @click="searchSubmit"
                style="margin: 0 10px;"> 搜索</el-button>
              <vxe-button @click="clearTableFilter" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
            </el-col>
            <el-col :span="4">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
                @keyup="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row
        highlight-current-row :loading="loading" :data="dataList">
        <vxe-table-column field="matchDate" title="比赛日期" sortable></vxe-table-column>
        <vxe-table-column field="matchName" title="赛事名称" sortable></vxe-table-column>
        <vxe-table-column field="matchLevel" title="赛事级别" sortable></vxe-table-column>
        <vxe-table-column field="matchKind" title="赛事类别" sortable></vxe-table-column>
        <vxe-table-column field="matchEvent" title="参赛项目" sortable></vxe-table-column>
        <vxe-table-column field="matchEventItem" title="参赛小项" sortable></vxe-table-column>
        <vxe-table-column field="name" title="运动员" sortable></vxe-table-column>
        <vxe-table-column field="delegation" title="代表队" sortable></vxe-table-column>
        <vxe-table-column field="matchRank" title="名词" sortable></vxe-table-column>
        <vxe-table-column field="recordBreak" title="破纪录" sortable></vxe-table-column>
        <vxe-table-column field="multiPlayerMatch" title="个人/团体" sortable></vxe-table-column>
        <vxe-table-column field="memo" title="备注" sortable></vxe-table-column>
        <vxe-table-column field="org" title="组织机构" sortable></vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.pageNum" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
  </div>
</template>

<script>
  import {
    statistics_org4provence,
    statistics_area,
    area2playerId,
    sport_all,
    sport_item_all,
    player_match_result,
    player_match_result_select,
    all4statistics,
  } from '@/api/statistics.js'
  import { match_level, match_kind, match_event, match_event_item, record_break } from '@/api/dict.js'
  export default {
    data() {
      return {
        doubleDate: '',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        defaultDataList: [],
        dataList: [],
        page: {
          pageNum: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        searchProps: [],
        dict_org: {},
        areaData: [],
        dict_player: {},
        dict_match_level: {},
        dict_match_kind: {},
        dict_match_event: {},
        dict_match_event_item: {},
        dict_delegation: {},
        dict_record_break: {},
        dict_coach: {},
        dict_status: { 1: '开通', 2: '审核', 3: '关闭' },
        dict_skillType: {
          1: "国际级运动健将",
          2: "运动健将",
          3: "一级运动员",
          4: "二级运动员",
          5: "三级运动员",
        },
        dict_sport: {},
        dict_sport_item: {},
        searchForm: {
          areaId: '',
          orgIdStr: [],
          matchLevelStr: [],
          matchKindStr: [],
          matchEventId: '',
          matchEventItemId: '',
          skillTypeId: '',
          matchRank: '',
          startDate: '',
          endDate: '',
        },
        orgData: [],
        matchEventItemData: {},
      }
    },
    created() {
      this.init_dict().then(() => {
        this.getOrg4player(this.page)
      })
    },
    methods: {
      searchSubmit() {
        let data = {}
        if (this.searchForm.orgIdStr.length != 0) data.orgIdStr = this.searchForm.orgIdStr.join(',')
        if (this.searchForm.matchLevelStr.length != 0) data.matchLevelStr = this.searchForm.matchLevelStr.join(',')
        if (this.searchForm.matchKindStr.length != 0) data.matchKindStr = this.searchForm.matchKindStr.join(',')
        if (this.searchForm.matchEventId) data.matchEventId = this.searchForm.matchEventId
        if (this.searchForm.matchEventItemId) data.matchEventItemId = this.searchForm.matchEventItemId
        if (this.searchForm.skillTypeId) data.skillTypeId = this.searchForm.skillTypeId
        if (this.searchForm.matchRank) data.matchRank = this.searchForm.matchRank
        data.pageNum = 1
        data.pageSize = this.page.pageSize
        if (this.doubleDate) {
          data.startDate = this.$moment(this.doubleDate[0]).format('YYYY-MM-DD') + ' 00:00:00'
          data.endDate = this.$moment(this.doubleDate[1]).format('YYYY-MM-DD') + ' 00:00:00'
        }
        player_match_result_select(data).then(res => {
          if (res.code === 200 && res.data.matches.length != 0) {
            this.page.totalResult = res.data.countNum
            this.init_data(res.data.matches)

          } else {
            this.defaultDataList = []
            this.dataList = this.defaultDataList
          }
        }).then(() => {

        })
      },
      clearTableFilter() {
        this.searchForm = {
          areaId: '',
          orgIdStr: [],
          matchLevelStr: [],
          matchKindStr: [],
          matchEventId: '',
          matchEventItemId: '',
          skillTypeId: '',
          matchRank: '',
          startDate: '',
          endDate: '',
        }

        this.page.pageNum = 1,
          this.page.pageSize = 10,
          this.doubleDate = ''
        this.getOrg4player(this.page)
      },
      sportChange(val) {
        this.searchForm.matchEventItemId = ''
        this.matchEventItemData = {}
        match_event_item(val).then(res => {
          this.matchEventItemData = res
        })
      },
      selectOrgAll() {
        this.searchForm.orgIdStr = []
        this.orgData.forEach(item => {
          this.searchForm.orgIdStr.push(item.orgId)
        })
      },
      areaChange(val) {
        this.orgData = []
        this.searchForm.orgIdStr = ''
        statistics_org4provence({ areaId: val }).then(res => {
          this.orgData = res.data
        })
      },
      getOrg4player() {
        let data = {}
        if (this.searchForm.orgIdStr.length != 0) data.orgIdStr = this.searchForm.orgIdStr.join(',')
        if (this.searchForm.matchLevelStr.length != 0) data.matchLevelStr = this.searchForm.matchLevelStr.join(',')
        if (this.searchForm.matchKindStr.length != 0) data.matchKindStr = this.searchForm.matchKindStr.join(',')
        if (this.searchForm.matchEventId) data.matchEventId = this.searchForm.matchEventId
        if (this.searchForm.matchEventItemId) data.matchEventItemId = this.searchForm.matchEventItemId
        if (this.searchForm.skillTypeId) data.skillTypeId = this.searchForm.skillTypeId
        if (this.searchForm.matchRank) data.matchRank = this.searchForm.matchRank
        data.pageNum = this.page.pageNum
        data.pageSize = this.page.pageSize

        player_match_result_select(data).then(res => {
          if (res.code === 200 && res.data.matches.length != 0) {
            this.init_data(res.data.matches)
            this.page.totalResult = Number(res.data.countNum)
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          // this.findList()
        })
      },
      init_data(data) {
        data.forEach(item => {
          item.name = this.dict_player[item.playerId]
          item.matchDate = this.$moment(item.matchDate).format('YYYY-MM-DD') == 'Invalid date' ? '' : this.$moment(
            item.matchDate).format('YYYY-MM-DD')
          item.matchLevel = this.dict_match_level[item.matchLevelId]
          item.matchKind = this.dict_match_kind[item.matchKindId]
          item.matchEvent = this.dict_match_event[item.matchEventId]
          item.matchEventItem = this.dict_match_event_item[item.matchEventItemId]
          item.delegation = this.dict_delegation[String(item.delegationId)]
          item.recordBreak = this.dict_record_break[item.recordBreakId]
          item.sport = this.dict_sport[item.sportId]
          item.sportItem = this.dict_sport_item[item.sportItemId]
          item.org = this.dict_org[item.recordOrgId]
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
        this.dataList = this.defaultDataList
      },
      init_dict() {

        return new Promise((resolve, reject) => {

          statistics_org4provence().then(res => {
            // console.log(1);
            this.orgData = res.data
            res.data.forEach(item => {
              this.dict_org[item.orgId] = item.name

            })
          })
          statistics_area().then(res => {

            this.areaData = res.data
          })
          match_level().then(res => {

            this.dict_match_level = res
          })
          match_kind().then(res => {

            this.dict_match_kind = res
          })

          match_event().then(res => {

            this.dict_match_event = res
          })
          match_event_item().then(res => {

            this.dict_match_event_item = res
          })
          record_break().then(res => {

            this.dict_record_break = res

          })
          //代表队
          all4statistics().then(res => {
            res.data.forEach(item => {
              this.dict_delegation[item.delegationId] = item.name
            })
            resolve()
          })
          //获取运动员
          this.dict_player = JSON.parse(window.sessionStorage.getItem("playerdata"))

        })
      },
      exportEvent() {
        this.loading = true
        setTimeout(() => {
          this.$refs.XTable.exportData({
            filename: '比赛成绩',
            isHeader: true,
            isFooter: true,
            data: this.defaultDataList
          })
          this.loading = false
        }, 100)
      },
      printEvent() {
        let topHtml = '<h2>比赛成绩</h2>'
        let num = this.page.pageSize
        this.page.pageSize = this.defaultDataList.length
        this.findList()
        setTimeout(() => {
          this.$refs.XTable.print({
            sheetName: '比赛成绩',
            beforePrintMethod: ({ content }) => {
              return topHtml + content
            }
          })
          this.page.pageSize = num
          // this.findList()
        }, 1000)
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = new RegExp(filterName, 'gi')
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
        } else {
          this.dataList = this.defaultDataList

          // this.findList()
        }
      },
      //分页
      handlePageChange({
        currentPage,
        pageSize
      }) {

        this.page.pageNum = currentPage
        this.page.pageSize = pageSize

        this.getOrg4player()
      },
      // sortChange() {
      //   this.page.pageSize = this.defaultDataList.length
      //   // this.findList()
      // },
      // findList() {
      //   this.loading = true
      //   setTimeout(() => {
      //     this.loading = false
      //     this.page.totalResult = this.defaultDataList.length
      //     this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
      //       .pageSize, this.page.currentPage * this.page.pageSize)
      //   }, 300)
      // },
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    padding: 10px;
    background-color: #FFFFFF;
  }
</style>
